package com.jike.jkgame;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import kankan.wheel.widget.adapters.AbstractWheelAdapter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jike.jkgame.data.Mission;
import com.jike.jkgame.data.MissionManager;

public class MissionListAdapter extends BaseAdapter {
	private LayoutInflater mInflater;
	private boolean mWheelScrolled = false;
	private int mActionMission = -1;
	private OnDoMissionListener mMissionListener;
	private List<Mission> mMissions;

//	// Wheel scrolled listener
//	OnWheelScrollListener mSlotScrolledListener = new OnWheelScrollListener() {
//		public void onScrollingStarted(WheelView wheel) {
//			mWheelScrolled = true;
//		}
//
//		public void onScrollingFinished(WheelView wheel) {
//			mWheelScrolled = false;
//			mMissionListener.onFinishMission(mActionMission, true);
//		}
//	};
//
//	// Wheel changed listener
//	private OnWheelChangedListener mSlotChangedListener = new OnWheelChangedListener() {
//		public void onChanged(WheelView wheel, int oldValue, int newValue) {
//			if (!mWheelScrolled && mMissionListener != null) {
//				mMissionListener.onFinishMission(mActionMission, true);
//			}
//		}
//	};

//	private void initWheel(WheelView wheel) {
//		wheel.setViewAdapter(new SlotMachineAdapter());
//		wheel.setCurrentItem((int) (Math.random() * 10));
//
//		wheel.addChangingListener(mSlotChangedListener);
//		wheel.addScrollingListener(mSlotScrolledListener);
//		wheel.setCyclic(true);
//		wheel.setEnabled(false);
//		wheel.setVisibleItems(2);
//	}

	/**
	 * Updates status
	 */
	private void updateStatus() {
		
	}
	
	@Override
    public void notifyDataSetChanged() {
	    mMissions = MissionManager.get().getMissions();
        super.notifyDataSetChanged();
    }

    public void setOnDoMissionListener(OnDoMissionListener l) {
		this.mMissionListener = l;
	}
	
	
	public MissionListAdapter() {
	    mInflater = LayoutInflater.from(JKApp.get());
	    mMissions = MissionManager.get().getMissions();
	}

	@Override
	public int getCount() {
		if (mMissions == null) {
			return 0;
		}
		return mMissions.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		
		Mission mission = null;
		if (getCount() > position) {
			mission= mMissions.get(position);
		}
		
		if (mission == null) {
			return null;
		}
		
		
		View v = convertView;
		if (v == null) {
			v = mInflater.inflate(R.layout.mission_item_layout, parent, false);
			ViewHolder h = new ViewHolder();
			h.idTv = (TextView) v.findViewById(R.id.tv_id);
			h.nameTv = (TextView) v.findViewById(R.id.tv_name);
			h.descriptTv = (TextView)v.findViewById(R.id.tv_discript);
			h.difficaultTv = (TextView) v.findViewById(R.id.tv_difficault);
			h.rewardsXPTv = (TextView) v.findViewById(R.id.tv_reward_xp);
			h.rewardsMTv = (TextView) v.findViewById(R.id.tv_reward_m);
			h.progressPb = (ProgressBar) v.findViewById(R.id.pb_progress);
			// h.slot = (WheelView) v.findViewById(R.id.slot_1);
			h.actionBtn = (Button) v.findViewById(R.id.btn_action);
			v.setTag(h);
		}
		
		final ViewHolder holder = (ViewHolder) v.getTag();
		holder.actionBtn.setTag(Integer.valueOf(position));
		// initWheel(holder.slot);

//		if (mWheelScrolled && position != mActionMission) {
//			holder.slot.stopScrolling();
//		}

		holder.actionBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mActionMission = mMissions.get(position).id;
				if (mMissionListener != null) {
					if (mMissionListener.onStartMission(mActionMission)) {
						// holder.slot.scroll(-350 + (int) (Math.random() * 50), 5000);
					} else {
						mMissionListener.onCancelMission(mActionMission);
					}
				}
			}
		});
		MissionManager manager = MissionManager.get();
		holder.idTv.setText(String.format("%d-%d-%d", manager.getCurrentCityIdx()+1, manager.getCurrentEventIndex()+1, position+1));
		holder.bindingData(mission);
		
		return v;
	}

	static class ViewHolder {
		public TextView idTv;
		public TextView nameTv;
		public TextView descriptTv;
		public TextView difficaultTv;
		public TextView rewardsXPTv;
		public TextView rewardsMTv;
		public ProgressBar progressPb;
		// public WheelView slot;
		public Button actionBtn;
		
		public void bindingData(Mission mission) {
			nameTv.setText(mission.name);
			descriptTv.setText(mission.descript);
			difficaultTv.setText("难度：" + String.valueOf(mission.energy));
			rewardsXPTv.setText("XP " + mission.reward_exp);
			rewardsMTv.setText("M " + mission.reward_cash);
			actionBtn.setText(mission.energy + "$ " + mission.buttonStr);
			actionBtn.setEnabled(mission.enabled);
			progressPb.setMax(mission.completeness);
			progressPb.setProgress(mission.finish_cnt);
		}
	}
	
	public static interface OnDoMissionListener {
		public boolean onStartMission(int missionId);
		public boolean onFinishMission(int missionId, boolean succeed);
		public boolean onCancelMission(int missionId);
	}

	/**
	 * Slot machine adapter
	 */
	private class SlotMachineAdapter extends AbstractWheelAdapter {
		// Image size
		final int IMAGE_WIDTH = 60;
		final int IMAGE_HEIGHT = 36;

		// Slot machine symbols
		private final int items[] = new int[] { android.R.drawable.star_big_on,
				android.R.drawable.stat_sys_warning,
				android.R.drawable.radiobutton_on_background,
				android.R.drawable.ic_delete };

		// Cached images
		private List<SoftReference<Bitmap>> images;

		// Layout inflater
		// private Context context;

		/**
		 * Constructor
		 */
		public SlotMachineAdapter() {
			images = new ArrayList<SoftReference<Bitmap>>(items.length);
			for (int id : items) {
				images.add(new SoftReference<Bitmap>(loadImage(id)));
			}
		}

		/**
		 * Loads image from resources
		 */
		private Bitmap loadImage(int id) {
			Bitmap bitmap = BitmapFactory.decodeResource(JKApp.get()
					.getResources(), id);
			Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH,
					IMAGE_HEIGHT, true);
			bitmap.recycle();
			return scaled;
		}

		@Override
		public int getItemsCount() {
			return items.length;
		}

		// Layout params for image view
		final LayoutParams params = new LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			ImageView img;
			if (cachedView != null) {
				img = (ImageView) cachedView;
			} else {
				img = new ImageView(JKApp.get());
			}
			img.setLayoutParams(params);
			SoftReference<Bitmap> bitmapRef = images.get(index);
			Bitmap bitmap = bitmapRef.get();
			if (bitmap == null) {
				bitmap = loadImage(items[index]);
				images.set(index, new SoftReference<Bitmap>(bitmap));
			}
			img.setImageBitmap(bitmap);

			return img;
		}
	}
}
